package com.zfast.config.interceptor;

import cn.hutool.core.date.DateUtil;
import com.zfast.config.constant.SessionKeyConst;
import com.zfast.config.entity.User;
import com.zfast.config.entity.Log;
import com.zfast.config.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Classname LogInterceptor
 * @Description None
 * @Date 2019/7/24 10:39
 * @Created by WDD
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Resource
    private Log logEntity;
    @Resource
    private LogService logService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.debug("访问路径：" + request.getRequestURI());
        handlerStr(handler);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String stringDate = DateUtil.now();
        String username = null;
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        if (request.getSession().getAttribute(SessionKeyConst.USER) != null) {
            User user = (User) request.getSession().getAttribute(SessionKeyConst.USER);
            username = user.getUsername();
        }
        String uri = request.getRequestURI();
        if (uri.equals("/manager/logList")) {
            return;
        }

        logEntity.setLogTime(stringDate);
        logEntity.setUsername(username);
        logEntity.setUri(uri);

        logService.insertByLog(logEntity);
    }

    public void handlerStr(Object handler) {
        //自用方法调用
        String str = "";
        if (handler != null) {
            str = handler.toString().trim();
            // 去掉修饰符和参数
            /*int index = str.indexOf(" ");
            if (index != -1)
                str = str.substring(index, str.length() - 1).trim();
            index = str.indexOf(" ");
            if (index != -1)
                str = str.substring(index + 1, str.length() - 1).trim();
            index = str.indexOf("(");
            if (index != -1)
                str = str.substring(0, index).trim();*/
        }
        //System.out.println("调用方法：" + str);
        log.debug("调用方法：" + str);
    }
}
